package org.xtlgen;

import javax.swing.JComponent;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;

/**
 * JComponent subclass used to display the graphics for the XtlGen system.
 */
public class XtlGenDisplay extends JComponent {
  /**
   * Create a new XtlGenDisplay.
   */
  public XtlGenDisplay() {
    super();
    drawingArea = null;
  }

  /**
   * Set the drawing to display. It will resize itself according to the
   * attributes of the given DrawingArea.
   */
  public void setDrawing(DrawingArea drawingArea) {
    this.drawingArea = drawingArea;
    Dimension dimension;
    if (drawingArea != null) {
      dimension =
        new Dimension((int)(drawingArea.getWidth()*drawingArea.getScale()),
                      (int)(drawingArea.getHeight()*drawingArea.getScale()));
    }
    else {
      dimension = new Dimension(500, 500);
    }
    setPreferredSize(dimension);
    setSize(dimension);
  }
  
  /**
   * Render the shape hierarchy, uses a DisplayCanvas to do the drawing.
   */
  public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;

    if (drawingArea != null) {
      DisplayCanvas canvas =  new DisplayCanvas(g2D);
      BasicStroke stroke = new BasicStroke((float) (1.0 / drawingArea.getScale()));
      
      g2D.scale(drawingArea.getScale(), drawingArea.getScale());
      g2D.setStroke(stroke);
      g2D.translate(-drawingArea.getXOrigin(), -drawingArea.getYOrigin());
      
      if (drawingArea != null) {
        drawingArea.draw(canvas);
      }
    }
  }

  /*
   * Fields.
   */
  DrawingArea drawingArea;
}